package com.vcredit.creditcat.service.loginPreview;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.vo.product.xyh.QueryResultVo;
import com.vcredit.creditcat.vo.product.xyh.ResultVo;
import com.vcredit.framework.exception.BaseException;
import com.vcredit.framework.util.HttpRequest;
import com.vcredit.framework.util.JacksonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 信用花登录预检处理类
 * Created by liaoshengjun on 2017/10/27.
 */
@Service("XYHPreviewService")
public class XYHPreviewService implements IProductPreview{
	@Value("${product.xyh.queryUrl}")
	private String queryUrl;

	private static final Integer TIMEOUT = 60; // 请求超时时间60s

	private static Logger logger = LoggerFactory.getLogger(XYHPreviewService.class);

	@Override
	public Integer checkExist(String mobile) throws Exception {
		Integer checkResult=0;
		Map queryParam =new HashMap();
		queryParam.put("mobile",mobile);
		try {
			String queryResultStr = HttpRequest.doJson(queryUrl, JacksonUtil.Obj2Json(queryParam), TIMEOUT);
			logger.info("信用花登录接口返回："+queryResultStr);
			ResultVo<QueryResultVo> result = JacksonUtil.Json2Obj(queryResultStr, new TypeReference<ResultVo<QueryResultVo>>(){});
			if(!result.getStatus().equals("000")) {//接口返回失败默认通过，防止信用花代码异常影响后续流程
				throw new BaseException("信用花接口调用失败："+ result.getStatus()+"手机号:"+mobile);
			}
			if(result.getData()!=null){
				QueryResultVo content = result.getData();
				//撞库
				if("1".equals(content.getListType())){
					checkResult=0;
				}else{
					if(StringUtils.isNotBlank(content.getChannel()) && !"502".equalsIgnoreCase(content.getChannel()) && !"503".equalsIgnoreCase(content.getChannel())){
						checkResult=0;
					}else{
						checkResult=1;
					}
				}

			}else{
				checkResult=1;
			}
		}catch (Exception e){
			logger.error("信用花登录预检接口调用失败"+"手机号:"+mobile,e);
			throw e;
		}
		return checkResult;
	}
}
